package com.cdp.zwy.zwy_manager_back_v1.controller;

import com.cdp.zwy.zwy_manager_back_v1.common.ErrorCode;
import com.cdp.zwy.zwy_manager_back_v1.common.Result;
import com.cdp.zwy.zwy_manager_back_v1.common.ServiceException;
import com.cdp.zwy.zwy_manager_back_v1.config.JwtUtils;
import com.cdp.zwy.zwy_manager_back_v1.entity.Account;
import com.cdp.zwy.zwy_manager_back_v1.entity.Admin;
import com.cdp.zwy.zwy_manager_back_v1.entity.Employee;
import com.cdp.zwy.zwy_manager_back_v1.service.AdminService;
import com.cdp.zwy.zwy_manager_back_v1.service.EmployeeService;
import com.cdp.zwy.zwy_manager_back_v1.service.MyUserDetails;
import com.cdp.zwy.zwy_manager_back_v1.service.MyUserDetailsService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import javax.swing.text.Element;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zwy
 * @version 1.0
 * @description: WebController(前台、接待处)
 * @date 2025/4/13 20:31
 */
@CrossOrigin
@RestController
public class WebController {
    @Resource
    private EmployeeService employeeService;
    @Resource
    private AdminService adminService;
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtils jwtTokenUtil;

    @Autowired
    private MyUserDetailsService userDetailsService;

    @PostMapping("/login")
    public Result createAuthenticationToken(@RequestBody Account authenticationRequest) throws Exception {
        //将认证的过程委托给AuthenticationManager
        // 创建一个包含角色信息的唯一用户名
        String usernameWithRole = authenticationRequest.getRole() + "::" + authenticationRequest.getUsername();
        Authentication authentication;
        try {
            // 委托AuthenticationManager进行认证,隐式调用MyUserDetailsService.loadUserByUsername
            authentication = authenticationManager.authenticate(
                    //这里传入的参数与你认证类型的构造函数参数一致，这里是用户密码认证用new UsernamePasswordAuthenticationToken
                    new UsernamePasswordAuthenticationToken(usernameWithRole, authenticationRequest.getPassword())
            );
        } catch (Exception e) {
            // 注意：这里的异常可能是用户名密码错误，也可能是角色不匹配等
            throw new Exception("用户名、密码或角色错误", e);
        }
        // 认证成功后，同样使用组合用户名来加载用户信息以生成Token
        final UserDetails userDetails = (UserDetails) authentication.getPrincipal();

        final String jwt = jwtTokenUtil.generateToken(userDetails);

        // 在返回的Token中，我们也应该包含用户的完整信息（包括角色）
        // 为了做到这一点，我们需要从数据库获取原始的用户对象
        Object userObject = ((MyUserDetails) userDetails).getUserObject();

        // 将JWT和用户信息一起返回给前端
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("token", jwt);
        responseData.put("user", userObject);

        return Result.success(responseData);
    }
    @PostMapping("/register")
    public Result register(@RequestBody Employee employee){
        Employee employee1 = employeeService.register(employee);
        return Result.success(employee1);
    }
    @PutMapping("/modifyPassword")
    public Result modifyPassword(@RequestBody Account account){
        if("EMP".equals(account.getRole())){
         Employee employee = employeeService.modifyPassword(account);
         return Result.success(employee);

        }
        if("ADMIN".equals(account.getRole())){
            Admin admin = adminService.modifyPassword(account);
            return Result.success(admin);
        }
        return Result.error("0000000000000","角色错误");
    }
}
